const PROT = 7777
const WHITE_LIST = ['/webhooks/server', '/webhooks/fe', '/webhooks/me']
const http = require('http')
const { exec } = require('child_process')
// wq125440
const secret = '5f7ca84c75e3f699ebe5d43650c698b6' // 随机密钥，要和gitee上的对应
// qihang
const secretMe = '8df16df500b213a371e6452d66f6b804' // 随机密钥，要和gitee上的对应

const server = http.createServer((req, res) => {
  if (req.method === 'POST' && WHITE_LIST.includes(req.url)) {
    req.on('data', (body) => {})
    req.on('end', () => {
      const signature = req.headers['x-gitee-token']
      if (signature === secret) {
        const shellStr = `sh /autoeploy/script/be_build.sh`
        exec(shellStr, (err, stdout, stderr) => {
          if (err) {
            console.error(`exec error: ${err}`)
            return
          }
          console.log(`stdout: ${stdout}`)
          if (stderr) {
            console.error(`stderr: ${stderr}`)
          }
        })
        res.writeHead(200, { 'Content-Type': 'text/plain' })
        res.end('自动打包触发成功～')
      } else if (signature === secretMe) {
        const shellStr = `sh /autoeploy/script/me_build.sh`
        exec(shellStr, (err, stdout, stderr) => {
          if (err) {
            console.error(`exec error: ${err}`)
            return
          }
          console.log(`stdout: ${stdout}`)
          if (stderr) {
            console.error(`stderr: ${stderr}`)
          }
        })
        res.writeHead(200, { 'Content-Type': 'text/plain' })
        res.end('自动打包触发成功～')
      } else {
        res.writeHead(401, { 'Content-Type': 'text/plain' })
        res.end('密钥不正确～')
      }
    })
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' })
    res.end('Not Found')
  }
})

server.listen(PROT, () => {
  console.log(`打包服务已运行，端口${PROT}`)
})
